﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WhittleList.Bll
{
    public partial class Project : IValidate, IConcurrent
    {

        partial void OnValidate(System.Data.Linq.ChangeAction action)
        {
            if (!IsValid)
                throw new Exceptions.ValidationException("Rule Violation Prevented Saving", GetRuleViolations());
        }
        #region IValidate Members

        public bool IsValid
        {
            get { return GetRuleViolations().Count() == 0; }
        }

        public virtual IEnumerable<RuleViolation> GetRuleViolations()
        {
            if (SiteId == 0)
                yield return new RuleViolation("SiteId", "SiteId must be set");
            if (string.IsNullOrEmpty(Name))
                yield return new RuleViolation("Name", "Project Name must be set");
            yield break;
        }

        #endregion

        public DateTime LastUpdated
        {
            get
            {
                return this.UTCLastUpdated.ToLocalTime();
            }
        }

        public DateTime Created
        {
            get
            {
                return this.UTCLastUpdated.ToLocalTime();
            }
        }

        internal void OnInerting(User currentUser)
        {
            this._LastUpdatedById = this._CreatedById = currentUser.Id;
            this._UTCLastUpdated = this._UTCCreated = DateTime.UtcNow;
        }

        internal void OnUpdating(User currentUser)
        {
            this._LastUpdatedById = currentUser.Id;
            this._UTCLastUpdated = DateTime.UtcNow;
        }

        public bool CheckConcurrent(System.Data.Linq.Binary cid)
        {
            if (this.CID == cid)
                return true;
            else
                return false;
        }

        public void EnsureConcurrent(System.Data.Linq.Binary cid)
        {
            if (this.CID != cid)
                throw new Exceptions.ConcurrencyException();
        }

    }
}
